import vue from 'vue';
import vueRouter from 'vue-router';
import routes from './routes.js';
import { isLogin } from "../utils/auth"

vue.use(vueRouter);

let router = new vueRouter({
    mode: 'history',
    routes
})


//解决路由跳转使用新导航跳转
const originalPush = vueRouter.prototype.push
const originalReplace = vueRouter.prototype.replace
// push
vueRouter.prototype.push = function push (location, onResolve, onReject) {
if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
return originalPush.call(this, location).catch(err => err)
}
// replace
vueRouter.prototype.replace = function push (location, onResolve, onReject) {
if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
return originalReplace.call(this, location).catch(err => err)
}



//用户判断登录跳转
router.beforeEach((to, from, next) => {
    let isAuth = isLogin();
    if (to.path == '/login' || to.path == '/register') {
        if (isAuth) {
            next('/');
        } else {
            next();
        }

    } else if (to.path == '/ShoppingCart' || to.path == '/generateorderandpay') {
        if (isAuth) {
            next();
        } else {
            next('/login');
        }
    } else {
        next();
    }
})
export default router;